package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetMeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.mapper.SetMealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * sky-take-out
 * com.sky.service.impl
 * 菜品业务层实现类
 * @author Ablecisi
 * @version 1.0
 * 2025/2/28
 * 星期五
 * 23:56
 */
@Service
public class DishServiceImpl implements DishService {

    private final DishMapper dishMapper;
    private final DishFlavorMapper dishFlavorMapper;
    private final SetMealDishMapper setMealDishMapper;
    private final SetMealMapper setMealMapper;

    @Autowired
    public DishServiceImpl(DishFlavorMapper dishFlavorMapper, DishMapper dishMapper, SetMealDishMapper setMealDishMapper, SetMealMapper setMealMapper) {
        this.dishFlavorMapper = dishFlavorMapper;
        this.dishMapper = dishMapper;
        this.setMealDishMapper = setMealDishMapper;
        this.setMealMapper = setMealMapper;
    }

    /**
     * 添加菜品
     *
     * @param dishDTO 菜品信息
     */
    @Override
    @Transactional
    public void addDishWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        dishMapper.insert(dish);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        Long dishId = dish.getId();

        if (flavors != null && ! flavors.isEmpty()) {
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            dishFlavorMapper.addFlavors(flavors);
        }
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO 查询条件
     * @return 查询结果
     */
    @Override
    public PageResult<DishVO> pageQueryDish(DishPageQueryDTO dishPageQueryDTO) {
        Page<DishVO> page = PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Page<DishVO> dishVOS = dishMapper.pageQueryDish(dishPageQueryDTO);

        dishVOS.close();
        page.close();
        return new PageResult<>(dishVOS.getTotal(), dishVOS.getResult());
    }

    /**
     * 查询菜品根据ID
     *
     * @param id 菜品ID
     * @return 菜品视图对象
     */
    @Override
    @Transactional
    public DishVO selectDishById(Long id) {
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectFlavorByDishId(id);
        Dish dish = dishMapper.getDishById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 删除菜品
     *
     * @param ids 需要删除的菜品的Id <br>
     * 如果在起售中的菜品或者在套餐中，不能简单的删除
     */
    @Override
    @Transactional
    public void deleteDishByIds(List<Long> ids) {
        // 判断是否在售卖中的菜品，不能删除
        for (Long id : ids) {
            Dish dish = dishMapper.getDishById(id);
            if (StatusConstant.ENABLE.equals(dish.getStatus()))
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        // 如果在套餐关联中，不能删除
        List<Long> setMealIds = setMealDishMapper.getSetMealIdsByDishIds(ids);
        if (setMealIds != null && ! setMealIds.isEmpty())
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);

        // 删除菜品数据
        dishMapper.deleteByIds(ids);

        // 删除菜品关联的口味数据
        dishFlavorMapper.deleteByDishIds(ids);

    }

    /**
     * 修改菜品
     *
     * @param dishDTO 菜品DTO
     */
    @Override
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateDish(dish);

        List<Long> dishIds = new ArrayList<>();
        dishIds.add(dishDTO.getId());
        dishFlavorMapper.deleteByDishIds(dishIds);

        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if (dishFlavors != null && ! dishFlavors.isEmpty()) {
            dishFlavors.forEach((dishFlavor) -> dishFlavor.setDishId(dishDTO.getId()));
            dishFlavorMapper.addFlavors(dishFlavors);
        }

    }

    /**
     * 修改菜品状态
     *
     * @param id 菜品ID
     * @param status 菜品状态
     */
    @Override
    public void updateDishStatus(Long id, Integer status) {
        // 判断是否关联有套餐，有起售中的套餐的菜品不能停售
        if (StatusConstant.DISABLE.equals(status)) {
            // 查询套餐ID
            List<Long> setMealIds = setMealDishMapper.getSetMealIdsByDishIds(new ArrayList<Long>(){{add(id);}});
            // 如果套餐ID不为空，说明有套餐关联
            if (setMealIds != null && ! setMealIds.isEmpty()) {
                for (Long setMealId : setMealIds) {
                    SetMeal setMeal = setMealMapper.querySetMealById(setMealId);
                    if (StatusConstant.ENABLE.equals(setMeal.getStatus())) {
                        throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL_NOT_DISABLE);
                    }
                }
            }
        }

        Dish dish = Dish.builder().id(id).status(status).build();
        dishMapper.updateDish(dish);
    }

    /**
     * 根据分类ID查询菜品
     *
     * @param dish 菜品
     * @return 菜品列表
     */
    @Override
    public List<DishVO> selectDishByCategoryId(Dish dish) {
        List<Dish> dishList = dishMapper.selectDishByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectFlavorByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;

    }
}
